<?php
namespace Beerus\Modules\DecoCompany\Controllers;

use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DecoCompanyCombo;
use Doraemon\service\DecoCompany\ComboManage;
use Doraemon\tools\Hhzurl;
use Illuminate\Support\MessageBag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\service\User;

class ComboController
{
    const CHECK_STATUS_DESC = [
        DecoCompanyCombo::CHECK_PASSED => "通过",
        DecoCompanyCombo::CHECK_NO_PASS => "不通过"
    ];

    public function list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $params = $request->input();

        $search = [];
        $search['combo_status'] = DecoCompanyCombo::STATUS_NORMAL;
        $uid_con = [];
        if (!empty($params['uid'])) {
            $uid_con[] = [$params['uid']];
        }
        //套餐id筛选
        if (!empty($params['id'])) {
            $search['id'] = $params['id'];
        }

        if (!empty($params['nick'])) {
            $uid = User::getUidByNick($params['nick']);
            $uid_con[] = [$uid];
        }
        if (!empty($params['check_status'])) {
            $search['check_status'] = $params['check_status'];
        }
        if (!empty($params['edit_time']['start'])) {
            $search['edit_time[>=]'] = strtotime($params['edit_time']['start']. ' 00:00:00');
        }
        if (!empty($params['edit_time']['end'])) {
            $search['edit_time[<=]'] = strtotime($params['edit_time']['end']. ' 23:59:59');
        }
        if (isset($params['is_superior']) && $params['is_superior'] != '') {
            $search['is_superior'] = $params['is_superior'];
        }

        if (!empty($params['main_area_code'])) {
            $area_uids = DecoCompany::select('uid', ['main_area_code' => $params['main_area_code']]);
            $uid_con[] = $area_uids;
        }

        // 多个uid查询取交集
        if (!empty($uid_con)) {
            $uid_inter = array_shift($uid_con);
            foreach ($uid_con as $uids) {
                $uid_inter = array_intersect($uid_inter, $uids);
            }
            $search['uid'] = $uid_inter;
        }

        $order = [];
        if (isset($params['_sort']) && $params['_sort']) {
            $order[$params['_sort']['column']] = strtoupper($params['_sort']['type']);
        }

        $map['AND'] = $search;
        $map['ORDER'] = $order ?: ['edit_time' => 'DESC'];
        $map['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = DecoCompanyCombo::listByCondition($map);
        $total = DecoCompanyCombo::countByCondition($search);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);

        // 装企城市
        $area_list = DecoCompany::select(['main_area_code', 'main_area_name'], ['main_area_code[!]' => '', 'main_area_name[!]' => '']);
        $area_map = array_column($area_list, 'main_area_name', 'main_area_code');

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $area_map) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function($filter) use ($area_map) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('check_status', '审核状态')->select(DecoCompanyCombo::CHECK_STATUS);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('edit_time', '更新时间')->date('Y-m-d');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('is_superior', '优质套餐')->select(DecoCompanyCombo::SUPERIOR_TEXT);
                    });
                    $filter->column(1 / 3, function ($filter) use ($area_map) {
                        $filter->equal('main_area_code', '城市')->select($area_map);
                    });
                    $filter->expand();
                });

                $grid->column("id", 'ID')->sortable();
                $grid->column('enterprise_name', '公司名称')->display(function () {
                    $info = DecoCompanyAuth::getByUid($this->uid);
                    return $info ? $info["enterprise_name"] : "";
                })->width(100);
                $grid->column("uid", '用户')->userBasicInfo();
                $grid->column("combo_name", '套餐名称');
                $grid->column("combo_price", '套餐价格')->display(function () {
                    return ComboManage::formatComboPrice($this->price_type, $this->combo_price, $this->combo_price_max);
                });
                /*$grid->column("combo_desc", '套餐亮点')->display(function () {
                    $combo_desc = array_filter(json_decode($this->combo_desc, true));
                    return implode("<br>", $combo_desc);
                });*/
                //$grid->column("design_num", '方案套数');
                $grid->column("style_tags", '装修风格')->display(function ($style_tags) {
                    return $style_tags ? join(',',json_decode($style_tags,true)) : "";
                });

                $grid->column("combo_type", '套餐类型')->display(function () {
                    return DecoCompanyCombo::COMBO_TYPE_MAP[$this->combo_type];
                });

                $grid->column("material", '材料清单')->display(function () {
                    $material = json_decode($this->material,true);
                    $auxiliary_material = json_decode($this->auxiliary_material,true);
                    if(!empty($material) || !empty($auxiliary_material)){
                        return "有";
                    }else{
                        return "无";
                    }
                });
                $grid->column("package_rule", '套餐适用规则')->display(function () {
                    $package_rule = json_decode($this->package_rule,true);
                    if(!empty($package_rule)){
                        return "有";
                    }else{
                        return "无";
                    }

                });

                $grid->column("work_duration", '限定工期')->display(function () {
                    return $this->work_duration . "天";
                });
                /*$grid->column("material", '主材项')->display(function ($material) {
                    return ComboManage::getCheckedOption($material);
                })->label('success')->width(100);*/
                /*$grid->column("contain_space", '空间项')->display(function ($contain_space) {
                    return ComboManage::getCheckedOption($contain_space);
                })->label('success')->width(100);*/
                $grid->column("check_status","审核状态")->using(DecoCompanyCombo::CHECK_STATUS)->label([
                    DecoCompanyCombo::CHECK_PENDING => 'warning',
                    DecoCompanyCombo::CHECK_PASSED => 'success',
                    DecoCompanyCombo::CHECK_NO_PASS => 'danger'
                ]);
                $grid->column('is_superior', '优质套餐')->display(function () {
                    if ($this->is_superior == 1) {
                        return "<span style='width:50px;display: inline-block;'>优质</span>";
                    }
                });
                $grid->column("check_time", '审核时间')->display(function () {
                    return $this->check_time ? date("Y-m-d H:i:s", $this->check_time) : '';
                });
                $grid->column("admin_id", '审核人员')->display(function () {
                    return "<span style='width:80px;display: inline-block;'>".Admin::user()->find($this->admin_id)->name."</span>";
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();

                    $actions->append('<a href="/admin/DecoCompany/combo/check/' . $actions->row->id . '" class="fa fa-check-square-o" style="width: 50px;font-size: 13px;">审核</a>');
                });
            });
        $tab = new Tab();
        $tab->add('套餐列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('套餐管理')
            ->description(' ')
            ->breadcrumb(['text' => '套餐列表']);
    }

    public function check(Request $request, Content $content, $id = 0)
    {
        $row = DecoCompanyCombo::getByCondition(['id'=>$id]);
        $row['combo_price'] = ComboManage::formatComboPrice($row['price_type'], $row['combo_price'], $row['combo_price_max']);
        $info = DecoCompanyAuth::getByUid($row['uid']);
        $row['enterprise_name'] = $info ? $info["enterprise_name"] : "";
        //$material = ComboManage::getCheckedOption($row['material']);
        //$row['material'] = implode(" ", $material);
        $contain_space = ComboManage::getCheckedOption($row['contain_space']);
        $row['contain_space'] = implode(" ", $contain_space);
        $combo_desc = array_filter(json_decode($row['combo_desc'], true));
        $row['combo_desc'] = implode(" ", $combo_desc);
        $head_imgs = json_decode($row['head_imgs'], true);
        $detail_imgs = json_decode($row['detail_imgs'], true);
        $material = json_decode($row['material'], true);
        $auxiliary_material = json_decode($row['auxiliary_material'], true);
        $content_config = json_decode($row['content_config'], true);
        $construct_process = explode(',',$row['construct_process']);
        $package_rule = json_decode($row['package_rule'],true);
        $guarantee_project = json_decode($row['guarantee_project'],true);
        $row['combo_type_str'] = DecoCompanyCombo::COMBO_TYPE_MAP[$row['combo_type']] ?? '无';

        $form = new Form($row);
        $tab = new Tab();
        $tab->add('审核', $form);

        $url = Hhzurl::getDomain() . "/decoration-company/package-detail?isPreview=1&pid={$row['id']}";
        $form->html('<div><a class="btn btn-primary" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'700px\', \'600px\'],
                                content: \'' . $url . '\'
                            });">预览</a></div>');
        $form->hidden('id');
        $form->display('uid', 'UID');
        $form->display('enterprise_name', '公司名称');
        $form->display('combo_name', '套餐名称');
        //$form->display('combo_desc', '套餐亮点');
        $form->display('combo_price', '套餐价格');
        $form->display('combo_type_str', '套餐类型');
        $form->divider("套餐头图");
        $html = '';
        foreach ($head_imgs as $item) {
            if ($item['pic_url']) {
                $html .= "<img src='{$item['pic_url']}' style='width:230px;margin:4px 5px;border: 5px solid #ddd;'>";
            }
        }
        $form->html($html);
        $form->divider();
        //$form->display('design_num', '方案套数');
        //$form->display('work_duration', '限定工期');
       /* $form->display('material', '主材项');*/
        //$form->display('contain_space', '空间项');
        $form->divider("套餐详情图");
        $html = '';
        foreach ($detail_imgs as $item) {
            if ($item['pic_url']) {
                $html .= "<img src='{$item['pic_url']}' style='width:230px;margin:4px 5px;border: 5px solid #ddd;'>";
            }
        }
        $form->html($html);
        $form->divider();

        if(!empty($content_config)){
            $form->divider("服务内容");
            $html = '';
            foreach ($content_config as $key=> $item) {
                if (!in_array($item,[DecoCompanyCombo::NOT_PROVIDE,DecoCompanyCombo::NOT_SHOW])) {
                    $element = DecoCompanyCombo::CONTENT_CONFIG_MAP[$key];
                    $option_name = $element['option_name'];
                    $option_item = $element['option_item'][$item];
                    $html .= "<span>".$option_name."：".$option_item."</span><br>";
                }
            }
            $form->html($html);
            $form->divider();
        }

        if(!empty($content_config)){
            $form->divider("不提供的服务内容");
            $html = '';
            foreach ($content_config as $key=> $item) {
                if (in_array($item,[DecoCompanyCombo::NOT_PROVIDE])) {
                    $element = DecoCompanyCombo::CONTENT_CONFIG_MAP[$key];
                    $option_name = $element['option_name'];
                    $html .= "<span>".$option_name."</span>，";
                }
            }
            $form->html($html);
            $form->divider();
        }

        if(!empty($material)){
            $form->divider("提供主材");
            $html = '';
            foreach ($material as $item) {
                if ($item['is_checked']==1) {
                    $html .= "<span>".$item['name']."：".$item['brand_name']."</span><br>";
                }
            }
            $form->html($html);
            $form->divider();
        }
        if(!empty($auxiliary_material)){
            $form->divider("提供辅材");
            $html = '';
            foreach ($auxiliary_material as $item) {
                if ($item['is_checked']==1) {
                    $html .= "<span>".$item['name']."：".$item['brand_name']."</span><br>";
                }
            }
            $form->html($html);
            $form->divider();
        }

        if(!empty($construct_process)){
            $form->divider("服务流程");
            $html = "整体工期：".$row['work_duration']."天<br>";
            foreach ($construct_process as $key=> $item) {
                    $element = DecoCompanyCombo::CONSTRUCT_PROCESS[$key+1];
                    $name = $element['name'];
                    $html .= $name."->";

            }
            $form->html(rtrim($html,'->'));
            $form->divider();
        }

        if(!empty($guarantee_project)){
            $form->divider("售后保障");
            $form->html("增项说明：".$guarantee_project['additional_explain']."<br>工程逾期说明：".$guarantee_project['overdue_explain']."<br>水电工程质保说明：".$guarantee_project['hydroelectric_explain']."<br>防水工程质保说明：".$guarantee_project['waterproofing_explain']."<br>基础施工保障说明：".$guarantee_project['foundation_explain']);
            $form->divider();
        }


        if(!empty($package_rule)){
            $form->divider("套餐规则");
            $form->html("产品条件：".$package_rule['applicable_condition']."<br>面积计算标准：".$package_rule['area_calculation']);
            $form->divider();
        }

        $form->select('check_status', '审核状态')->setWidth(3, 2)->options(self::CHECK_STATUS_DESC)
            ->when(DecoCompanyCombo::CHECK_NO_PASS, function ($form) {
                $form->textarea('check_reason', '审核未通过理由');
            })
            ->when(DecoCompanyCombo::CHECK_PASSED, function ($form) {
                $form->radio('is_superior', '优质套餐')->options(DecoCompanyCombo::SUPERIOR_TEXT)
                    ->default(DecoCompanyCombo::NOT_SUPERIOR);
            })
            ->required('必须选择');
        
        $form->disableReset();

        $form->confirm('确认操作审核吗？');

        $form->action('/admin/DecoCompany/combo/submit');

        return $content
            ->header('套餐管理')
            ->description('套餐审核')
            ->breadcrumb(['text' => '套餐审核'])
            ->body($tab);
    }

    public function submit(Request $request)
    {
        $params = $request->input();
        unset($params['_token']);

        if ($params['check_status'] == DecoCompanyCombo::CHECK_NO_PASS && empty($params['check_reason'])) {
            $error = new MessageBag([
                'title' => '请填写审核不通过的理由'
            ]);
            return back()->withInput()->with(compact('error'));
        }

        $combo_info = DecoCompanyCombo::getComboById($params['id']);
        if (empty($combo_info)) {
            $error = new MessageBag([
                'title' => '套餐不存在'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        $uid = $combo_info['uid'];

        if ($params['check_status'] != DecoCompanyCombo::CHECK_PASSED) {
            $params['is_superior'] = DecoCompanyCombo::NOT_SUPERIOR;
        }

        $data = [];
        $data['is_superior'] = $params['is_superior'];
        $data['check_status'] = $params['check_status'];
        $data['check_time'] = time();
        $data['admin_id'] = Admin::user()->id;
        $data['check_reason'] = $params['check_reason'] ?? '';
        $res = DecoCompanyCombo::updateInfo($data, ['id'=>$params['id']]);
        if ($res) {
            $success = new MessageBag([
                'title' => '审核成功'
            ]);
            return redirect("/admin/DecoCompany/combo/list")->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '审核失败，请稍后重试'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

}
